package com.outlook.servlet.tree;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.outlook.util.HttpHeaderConfigHelper;
import com.outlook.util.RandomUtil;

/**
 * 
 * @author watson
 *
 */
public class NoteServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static Log loger = LogFactory.getLog(NoteServlet.class);

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpHeaderConfigHelper.configJSONHeader(request, response);

		JSONArray array = null;
		String type = request.getParameter("type");
		if(type != null) {
			type = type.toLowerCase();
			final String id = request.getParameter("id");
			if("load".equals(type)) {
				loger.debug("from client request for loading with id:" + id);
				array = getNote();
			} else if("create".equals(type)) {
				loger.debug("from client request for loading with id: " + id);
			} else if("update".equals(type)) {
				loger.debug("from client request for updating with id: " + id);
			} else if("delete".equals(type)) {
				loger.debug("from client request for deleting with id: " + id);
			} else if("save".equals(type)) {
				loger.debug("from client request for saving with id: " + id);
			} else
				loger.debug("from client request for saving with id: " + id + " and type: "+type);
		}
		PrintWriter out = response.getWriter();
		out.print(array);
	}

	public JSONArray getNote() {
		JSONArray array = new JSONArray();
		JSONObject object = new JSONObject();
		for(int i=0; i<10; i++) {
			JSONObject tmp = new JSONObject();
			tmp.put("id", i);
			if(RandomUtil.random.nextBoolean()) {
				tmp.put("r_url", "load?type=load");
				tmp.put("c_url", "create.html");
				tmp.put("u_url", "edit.html");
				tmp.put("d_url", "delete.html");
			}
			object.put("attributes", tmp);
			
			if(RandomUtil.random.nextBoolean()) {
				object.put("state", "closed");
			}
			
			object.put("data", RandomUtil.getRandomString());
			array.add(object);
		}
		return array;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
